package com.roc.web.action.count;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.ChangeAgentCountBean;
import com.roc.bean.ChangeCheckCountBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.BlackList;
import com.roc.pojo.MerinfoStop;
import com.roc.pojo.Operators;
import com.roc.pojo.WindControllSta;
import com.roc.service.IExcelService;
import com.roc.service.count.ChangeCheckCountService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.windcontroll.WindControllStaSearchCondition;

/**
 * 变更审核统计
 * @ClassName: ChangeCheckCountAction
 * @Description: TODO
 * @author jdd
 * @date 2017年5月8日
 *
 */
@Action
@Component
@Scope("prototype")
@Namespace("/changeCheckCount")
public class ChangeCheckCountAction  extends PaginationBaseAction{
	
	 /**
	  * @Fields serialVersionUID : TODO
	  */
	    
	private static final long serialVersionUID = 1L;

	private Logger logger=LogManager.getLogger(ChangeCheckCountAction.class);

	private ChangeCheckCountSearchCondition searchCondition;
	
	
	@Autowired
	private ChangeCheckCountService  changeCheckCountService;
	
	@Autowired
	private IPageService  pageService;
	
	@Autowired
	private IExcelService excelService;
	
	private ByteArrayInputStream excelFile;
	
	/**
	 * 变更审核人员统计
	 * 跳转主页面
	 * @Title: init
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value="init",results={ @Result(name="success",location="/pages/count/ChangeCheckCountJsp.jsp")})
	public String init(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	
	}
	/**
	 * 审核查询
	 * @Title: queryChangeCheck
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value="queryChangeCheck",results={@Result(name="success",location="/pages/count/ChangeCheckCountJsp.jsp")})
	public String queryChangeCheck(){
		
		if(searchCondition==null){
			searchCondition=(ChangeCheckCountSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ChangeCheckCountSearchCondition();
			}
		}
		
		List<Object> params = new ArrayList<Object>();
		logger.info("查询条件,起始时间："+searchCondition.getMinDate()+" 结束时间："+searchCondition.getMaxDate());
		
		try {
			
			logger.info("转换后的时间格式："+new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMinDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMinDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMaxDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMinDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMaxDate())));
			
			int rows = changeCheckCountService.queryChangeCheckCount(params);
			List<ChangeCheckCountBean> ccList = new ArrayList<ChangeCheckCountBean>();
			if(rows>0){
				ccList = changeCheckCountService.queryChangeCheckList(params, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			getRequest().setAttribute("ccList", ccList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询风控统计数据异常："+e);
		}
		return SUCCESS;
	}
	/**
	 * 变更审核统计--导出
	 * @Title: exportChangeCheck
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value = "exportChangeCheck", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/windControllSta/windControllStaJsp.jsp") })
	public String exportChangeCheck(){
		
		logger.info("导出风控审核统计excel开始");
		
		if(searchCondition==null){
			searchCondition=(ChangeCheckCountSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ChangeCheckCountSearchCondition();
			}
		}
		
		List<Object> params = new ArrayList<Object>();
		logger.info("导出条件,起始时间："+searchCondition.getMinDate()+" 结束时间："+searchCondition.getMaxDate());
		
		try {
			logger.info("转换后的时间格式："+new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMinDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMinDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMaxDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMinDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getMaxDate())));
			
			int rows = changeCheckCountService.queryChangeCheckCount(params);
			List<ChangeCheckCountBean> ccList = new ArrayList<ChangeCheckCountBean>();
			if(rows>0){
				ccList = changeCheckCountService.queryChangeCheckList(params, calcuStart(getCurrentPage()), rows);
			}
			
			logger.info("rows:" + rows + "    searchRsList.size():"+ ccList.size());
			
			HSSFWorkbook work = excelService.exportChangeCheckList(ccList, searchCondition.getMinDate(),searchCondition.getMaxDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出风控审核统计excel结束");
		} catch (Exception e) {
			logger.info("导出风控审核统计数据异常："+e);
		}
		return SUCCESS;
	}

	/**
	 * 审核统计  -- 代理商
	 * 跳转主页面
	 * @Title: init
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value="agentInit",results={ @Result(name="success",location="/pages/count/AgentChangeJsp.jsp")})
	public String agentInit(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	
	}
	/**
	 * 审核查询   ---代理商
	 * @Title: queryChangeCheck
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value="queryChangeCheckAgent",results={@Result(name="success",location="/pages/count/AgentChangeJsp.jsp")})
	public String queryChangeCheckAgent(){
		
		if(searchCondition==null){
			searchCondition=(ChangeCheckCountSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ChangeCheckCountSearchCondition();
			}
		}
		logger.info("查询条件,起始时间："+searchCondition.getStatDate()+" 结束时间："+searchCondition.getEndDate());
		try {
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
				List<ChangeAgentCountBean> cclist=new ArrayList<ChangeAgentCountBean>();
				if(searchRsList!=null&&searchRsList.size()>0)
				{
					Iterator<?> iterator=searchRsList.iterator();
					while(iterator.hasNext())
					{
						Object[] obj=(Object[]) iterator.next();
						ChangeAgentCountBean cc=new ChangeAgentCountBean();
						cc.setAgentId(Constance.Null2EmptyTrim(obj[0]));
						cc.setAgentName(Constance.Null2EmptyTrim(obj[1]));
						cc.setDealCode(Constance.Null2EmptyTrim(obj[2]));
					//	cc.setTotal(Constance.Null2EmptyTrim(obj[3]));
						cc.setPassCount(Constance.Null2EmptyTrim(obj[3]));
						cc.setNoPassCount(Constance.Null2EmptyTrim(obj[4]));
						cc.setCompanyName(Constance.Null2EmptyTrim(obj[5]));
						cclist.add(cc);
					}
				}
			
			getRequest().setAttribute("cclist", cclist);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询风控统计数据异常："+e);
		}
		return SUCCESS;
	}
	/**
	 * 导出商户审核统计 -- 代理商
	 * @Title: exportChangeCheckAgent
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value = "exportChangeCheckAgent", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/count/AgentChangeJsp") })
	public String exportChangeCheckAgent(){
		
		logger.info("导出风控审核统计excel开始");
		
		if(searchCondition==null){
			searchCondition=(ChangeCheckCountSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ChangeCheckCountSearchCondition();
			}
		}
		logger.info("查询条件,起始时间："+searchCondition.getStatDate()+" 结束时间："+searchCondition.getEndDate());
		try {
			
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<ChangeAgentCountBean> ccList=new ArrayList<ChangeAgentCountBean>();
			dealWith(ccList,searchRsList);
			logger.info("rows:" + rows + "    searchRsList.size():"+ searchRsList.size());
			HSSFWorkbook work=excelService.exportChangeCheckAgentList(ccList,searchCondition.getStatDate(),searchCondition.getEndDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出风控审核统计excel结束");
		} catch (Exception e) {
			logger.info("导出风控审核统计数据异常："+e);
		}
		return SUCCESS;
	}

	private List<ChangeAgentCountBean> dealWith(List<ChangeAgentCountBean> ccList,List<Object> searchRsList){
		if(searchRsList!=null&&searchRsList.size()>0)
		{
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				ChangeAgentCountBean cc=new ChangeAgentCountBean();
				cc.setAgentId(Constance.Null2EmptyTrim(obj[0]));
				cc.setAgentName(Constance.Null2EmptyTrim(obj[1]));
				cc.setDealCode(Constance.Null2EmptyTrim(obj[2]));
			//	cc.setTotal(Constance.Null2EmptyTrim(obj[3]));
				cc.setPassCount(Constance.Null2EmptyTrim(obj[3]));
				cc.setNoPassCount(Constance.Null2EmptyTrim(obj[4]));
				cc.setCompanyName(Constance.Null2EmptyTrim(obj[5]));
				ccList.add(cc);
			}
		}
		return ccList;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_QUERY_CHANGE_CHECK, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (ChangeCheckCountSearchCondition)getSession().getAttribute(SEARCH_SESSION_QUERY_CHANGE_CHECK);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public ChangeCheckCountSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ChangeCheckCountSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	public ByteArrayInputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(ByteArrayInputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName = "变更审核统计审核统计" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

}
